package com.runen.infinitemovement.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.module.LoadMoreModule;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.runen.infinitemovement.App;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.DynamicStateDetailsActivity;
import com.runen.infinitemovement.activity.MyHomeActivityV2;
import com.runen.infinitemovement.activity.PhotoActivity;
import com.runen.infinitemovement.activity.WebActivity;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.DynamicEntity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.widget.goodview.GoodView;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.infinitemovement.widget.popupwind.ShareAndDeteleWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class MyDynamicStateAdapterV2 extends BaseQuickAdapter<DynamicEntity.DataBean, BaseViewHolder> implements LoadMoreModule {
    private Context context;
    private MyDynamicStatePictureAdapter dynamicStatePictureAdapter;
    private MyDynamicStateChallengeAdapter challengeAdapter;
    private MyDynamicStateCommentAdapter commentAdapter;
    private int viewFlag;

    private float scrollX;
    private float scrollY;

    public MyDynamicStateAdapterV2(Context context, int viewFlag) {
        super(R.layout.item_my_dynamic_state);
        this.context = context;
        this.viewFlag = viewFlag;
    }

    @Override
    protected void convert(BaseViewHolder helper, DynamicEntity.DataBean item) {
        TextView tv_focus = helper.getView(R.id.tv_focus);
        LinearLayout ll_like = helper.getView(R.id.ll_like);
        ImageView iv_like = helper.getView(R.id.iv_like);
        ImageView iv_more = helper.getView(R.id.iv_more);
        RoundedCornersImage rci_user_header = helper.getView(R.id.rci_user_header);
        TextView tv_nickName = helper.getView(R.id.tv_nickName);
        TextView tv_time = helper.getView(R.id.tv_time);
        TextView tv_check_more = helper.getView(R.id.tv_check_more);
        TextView tv_describe = helper.getView(R.id.tv_describe);
        RecyclerView rv_picture = helper.getView(R.id.rv_picture);
        RecyclerView rv_challenge = helper.getView(R.id.rv_challenge);
        RecyclerView rv_comment = helper.getView(R.id.rv_comment);
        TextView tv_like = helper.getView(R.id.tv_like);
        TextView tv_comment = helper.getView(R.id.tv_comment);
        RelativeLayout rl_img_or_prise = helper.getView(R.id.rl_img_or_prise);
        LinearLayout ll_cheng_jiu = helper.getView(R.id.ll_cheng_jiu);
        ImageView iv_map_data = helper.getView(R.id.iv_map_data);
        RoundedCornersImage rci_chengjui = helper.getView(R.id.rci_chengjui);
        TextView tv_start_end_name = helper.getView(R.id.tv_start_end_name);
        TextView tv_rank_num = helper.getView(R.id.tv_rank_num);
        TextView tv_prize = helper.getView(R.id.tv_prize);
        ImageView iv_prize = helper.getView(R.id.iv_prize);
        View v_line = helper.getView(R.id.v_line);
        LinearLayout ll_content_info = helper.getView(R.id.ll_content_info);
        if (item.certificateInfo != null || !TextUtils.isEmpty(item.motionImage)) {
            rl_img_or_prise.setVisibility(View.VISIBLE);
        } else {
            rl_img_or_prise.setVisibility(View.GONE);
        }
        if (item.certificateInfo != null) {
            ll_cheng_jiu.setVisibility(View.VISIBLE);
            GlideUtils.loadImage(context, item.certificateInfo.cover, rci_chengjui);
            String string = "%s - %s";
            tv_start_end_name.setText(String.format(string, item.certificateInfo.startPoint, item.certificateInfo.endPoint));
            tv_rank_num.setText(String.valueOf(item.certificateInfo.rank));
            tv_prize.setText(item.certificateInfo.prize);
            GlideUtils.loadImage(context, item.certificateInfo.medalUrl, iv_prize);
        } else {
            ll_cheng_jiu.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(item.motionId)) {
            iv_map_data.setVisibility(View.VISIBLE);
            String imgUrl = String.format(Constant.IMG_SPORT_RECORD, item.motionId);
//            GlideUtils.loadImage(context, imgUrl, iv_map_data);
            Glide.with(App.getInstance()).load(imgUrl).error(R.mipmap.ico_default_img).into(iv_map_data);
            iv_map_data.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent inte = new Intent(context, WebActivity.class);
                    String url = Constant.SPORTS_DETAILS;
                    inte.putExtra("LINK_URL", String.format(url, item.motionId));
                    context.startActivity(inte);
                }
            });
        } else {
            iv_map_data.setVisibility(View.GONE);
        }


        if (viewFlag == 0) {
            tv_focus.setVisibility(View.VISIBLE);
            iv_more.setVisibility(View.GONE);
            tv_check_more.setVisibility(View.GONE);
        } else {
            tv_focus.setVisibility(View.GONE);
            iv_more.setVisibility(View.GONE);
            if (item.commentNumber >= 2) {
                tv_check_more.setVisibility(View.VISIBLE);
            } else {
                tv_check_more.setVisibility(View.GONE);
            }

        }

        if (UserAPI.getUserId().equals(item.userId)) {
            tv_focus.setVisibility(View.GONE);
        } else {
            tv_focus.setVisibility(View.VISIBLE);
            if (item.isConcerned) {
                tv_focus.setText("已关注");
                tv_focus.setTextColor(CommonUtil.getColor(R.color.color_FF666666));
                tv_focus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ffd7d7d7_stroke_360dp));
                tv_focus.setVisibility(View.GONE);
            } else {
                tv_focus.setText("关注");
                tv_focus.setTextColor(CommonUtil.getColor(R.color.color_FFF63E5A));
                tv_focus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ffffeeee_360dp));
                tv_focus.setVisibility(View.VISIBLE);
            }
        }

        GlideUtils.loadImage(context, item.headImgUrl + "?x-oss-process=image/resize,m_fill,w_144,h_144", rci_user_header);
        tv_nickName.setText(item.nickname);
        if (!TextUtils.isEmpty(item.createTime)) {
            tv_time.setText(TimeUtil.converFromSecondTime(TimeUtil.getDateTimeToLong(TimeUtil.dealDateFormat1(item.createTime))));
        }
        tv_describe.setText(item.content);
        if (item.isLike) {
            GlideUtils.loadImage(context, CommonUtil.getDrawable(R.mipmap.ico_praised), iv_like);
        } else {
            GlideUtils.loadImage(context, CommonUtil.getDrawable(R.mipmap.ico_like), iv_like);
        }
        tv_like.setText(String.valueOf(item.likeNumber));
        tv_comment.setText(String.valueOf(item.commentNumber));
        /**
         * 图片
         */
        LinearLayoutManager layoutManager = new GridLayoutManager(context, 3);
        rv_picture.setLayoutManager(layoutManager);
        dynamicStatePictureAdapter = new MyDynamicStatePictureAdapter(context);
        rv_picture.setAdapter(dynamicStatePictureAdapter);
        List<String> urls = new ArrayList<String>();
        if (null != item.images && item.images.size() > 0) {
            for (int i = 0; i < item.images.size(); i++) {
                urls.add(item.images.get(i));
            }
            rv_picture.setVisibility(View.VISIBLE);
            dynamicStatePictureAdapter.setNewData(item.images);
        } else {
            rv_picture.setVisibility(View.GONE);
        }
        rv_picture.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    scrollX = event.getX();
                    scrollY = event.getY();
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (v.getId() != 0 && Math.abs(scrollX - event.getX()) <= 5 && Math.abs(scrollY - event.getY()) <= 5) {
                        //recyclerView空白处点击事件
                        Intent intent = new Intent(context, DynamicStateDetailsActivity.class);
                        intent.putExtra("userId", item.userId);
                        intent.putExtra("dynamicId", item.id);
                        context.startActivity(intent);
                    }
                }
                return false;
            }
        });
        dynamicStatePictureAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ArrayList<String> list = new ArrayList<>();
                for (int j = 0; j < urls.size(); j++) {
                    list.add(urls.get(j));
                }
                Intent intent = new Intent(context, PhotoActivity.class);
                intent.putExtra("position", position);
                intent.putStringArrayListExtra("list", list);
                context.startActivity(intent);
            }
        });

        /**
         * 挑战
         */
//        StaggeredGridLayoutManager challengeLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        LinearLayoutManager challengeLayoutManager = new LinearLayoutManager(context);
        challengeLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_challenge.setLayoutManager(challengeLayoutManager);
        challengeAdapter = new MyDynamicStateChallengeAdapter(context);
        rv_challenge.setAdapter(challengeAdapter);
        if (null != item.activeNames && item.activeNames.size() > 0) {
            rv_challenge.setVisibility(View.VISIBLE);
            challengeAdapter.setNewData(item.activeNames);
        } else {
            rv_challenge.setVisibility(View.GONE);
        }

        /**
         * 评论
         */
        LinearLayoutManager commentLayoutManager = new LinearLayoutManager(context);
        commentLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_comment.setLayoutManager(commentLayoutManager);
        commentAdapter = new MyDynamicStateCommentAdapter(context);
        rv_comment.setAdapter(commentAdapter);
        if (null != item.commentsPageDto && item.commentsPageDto.size() > 0) {
            commentAdapter.setNewData(item.commentsPageDto);
            v_line.setVisibility(View.VISIBLE);
            ll_content_info.setVisibility(View.VISIBLE);
        } else {
            v_line.setVisibility(View.GONE);
            ll_content_info.setVisibility(View.GONE);
        }

        iv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(item, helper.getAdapterPosition());
            }
        });
        tv_describe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DynamicStateDetailsActivity.class);
                intent.putExtra("userId", item.userId);
                intent.putExtra("dynamicId", item.id);
                context.startActivity(intent);
            }
        });
        tv_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DynamicStateDetailsActivity.class);
                intent.putExtra("userId", item.userId);
                intent.putExtra("dynamicId", item.id);
                context.startActivity(intent);
            }
        });
        tv_check_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DynamicStateDetailsActivity.class);
                intent.putExtra("userId", item.userId);
                intent.putExtra("dynamicId", item.id);
                context.startActivity(intent);
            }
        });
        ll_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.isLike) {
                    item.likeNumber = item.likeNumber - 1;
                    item.isLike = false;
                    GlideUtils.loadImage(context, CommonUtil.getDrawable(R.mipmap.ico_like), iv_like);
                } else {
                    item.likeNumber = item.likeNumber + 1;
                    item.isLike = true;
                    GoodView goodView = new GoodView(context);
                    goodView.setImage(R.mipmap.ico_praised);
                    goodView.show(iv_like);
                    GlideUtils.loadImage(context, CommonUtil.getDrawable(R.mipmap.ico_praised), iv_like);
                }
                onPraise(item);
                tv_like.setText(String.valueOf(item.likeNumber));
            }
        });

        rci_user_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MyHomeActivityV2.class);
                intent.putExtra("userId", item.userId);
                context.startActivity(intent);
            }
        });

        tv_focus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!item.isConcerned) {
                    item.isConcerned = true;
                    tv_focus.setText("已关注");
                    tv_focus.setTextColor(CommonUtil.getColor(R.color.color_FF666666));
                    tv_focus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ffd7d7d7_stroke_360dp));
                    addFocus(item);
                    tv_focus.setVisibility(View.GONE);
                } else {
                    item.isConcerned = false;
                    tv_focus.setText("关注");
                    tv_focus.setTextColor(CommonUtil.getColor(R.color.color_FFF63E5A));
                    tv_focus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ffffeeee_360dp));
                    onCancelFocus(item);
                    tv_focus.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void onPraise(DynamicEntity.DataBean item) {
        JSONObject object = new JSONObject();
        try {
            object.put("likeDataId", item.id);
            object.put("toLikeUserId", item.userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().onPraise(object.toString(), item.isLike, new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() != 0) {
                    ToastUtils.showShort(response.getMessage());
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
//                if (item.isLike) {
//                    ToastUtils.showShort("点赞成功");
//                } else {
//                    ToastUtils.showShort("取消点赞成功");
//                }
            }
        });
    }

    /**
     * 分享和删除
     */
    private void showPopupWindow(DynamicEntity.DataBean item, int position) {
        ShareAndDeteleWindow popupwiindow = ShareAndDeteleWindow.getInstance(context);
        popupwiindow.show();
        popupwiindow.setShareAndDeleteLisener(new ShareAndDeteleWindow.OnShareAndDeleteListener() {
            @Override
            public void onShare() {

            }

            @Override
            public void onDelete() {
                CommonDialog.getInstance(context, "", "确定删除？", "取消", "删除", 0).setOnClickListener(new CommonDialog.OnClickListener() {
                    @Override
                    public void onSendListener() {
                    }

                    @Override
                    public void onDismiss() {
                        onGoDelete(item, position);
                    }
                });
            }
        });
    }

    /**
     * 删除动态
     *
     * @param item
     */
    private void onGoDelete(DynamicEntity.DataBean item, int position) {
        JSONObject object = new JSONObject();
        try {
            object.put("dynamicId", item.id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new ActivityAPI().onDelete(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    ToastUtils.showShort("删除成功");
                    remove(position);
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();

            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
            }
        });


    }

    /**
     * 关注
     *
     * @param item
     */
    private void addFocus(DynamicEntity.DataBean item) {
        JSONObject object = new JSONObject();
        try {
            object.put("concernedUserId", item.userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().addFocus(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                ToastUtils.showShort("关注成功");
            }
        });

    }

    /**
     * 取消关注
     *
     * @param item
     */
    private void onCancelFocus(DynamicEntity.DataBean item) {
        JSONObject object = new JSONObject();
        try {
            object.put("unConcernedUserId", item.userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().cancelFocus(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                ToastUtils.showShort("取消关注成功");
            }
        });

    }
}
